﻿using Microsoft.EntityFrameworkCore;

namespace MarketManagementSystem.Services
{
    public abstract class BaseService<TEntity, TDbContext> where TEntity : class where TDbContext : DbContext
    {
        protected readonly TDbContext _dbContext;

        protected readonly ILogger<BaseService<TEntity, TDbContext>> _logger;

        protected BaseService(TDbContext dbContext, ILogger<BaseService<TEntity, TDbContext>> logger)
        {
            _dbContext = dbContext;
            _logger = logger;
        }


        public virtual async Task<TEntity> GetByIdAsync(int id)
        {
            TEntity entity = await _dbContext.Set<TEntity>().FindAsync(id);

            if (entity == null)
            {
                _logger.Log(logLevel:LogLevel.Error, "Entity not found");
                throw new Exception("Entity not found.");
            }

            return entity;
        }



        public virtual async Task<IEnumerable<TEntity>> GetAllAsync()
        {
            return await _dbContext.Set<TEntity>().ToListAsync();
        }

        public virtual async Task<TEntity> AddAsync(TEntity entity)
        {
            _dbContext.Set<TEntity>().Add(entity);
            await _dbContext.SaveChangesAsync();
            return entity;
        }

        public virtual async Task<TEntity> UpdateAsync(TEntity entity)
        {
            _dbContext.Entry(entity).State = EntityState.Modified;
            await _dbContext.SaveChangesAsync();
            return entity;
        }

        public virtual async Task<bool> DeleteAsync(int id)
        {
            var entity = await GetByIdAsync(id);
            if (entity == null)
            {
                _logger.LogError("Entity not found");
                return false;
            }

            _dbContext.Set<TEntity>().Remove(entity);
            await _dbContext.SaveChangesAsync();
            return true;
        }
    }

}
